<template>
  <div>
    <!--announcementTitle: '公告管理',
      newProblem: '新增公告',
      delProblem: '删除公告',
      headline: '标题',
      isRelease: '是否发布',
      publisher: '发布人',
      relateDetails:'公告详情',
      releOrganization: '发布组织',
      releaseTime: '发布时间',
      type: '类型',
      operation: '操作',
      release: '发布',
      clickDetails: '点击查看详情'
      -->
    <div class="page-header">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="page-header__title">{{$t('pages.announcement.announcementTitle')}}</div>
        </el-col>
        <el-col :span="16" class="text-right">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item>
              <el-input
                :placeholder="$t('pages.help.input_search_placeholder')"
                @keydown.native.13="getDataList"
                v-model="formInline.searchInput">
                <i slot="suffix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </el-form-item>
            <el-button type="danger"  @click="getDataList()">搜索</el-button>
            <el-button type="primary" icon="el-icon-plus"  @click="newHandle()">{{$t('pages.announcement.newProblem')}}</el-button>
            <el-button type="danger" icon="el-icon-minus"  @click="delBtn()">{{$t('pages.announcement.delProblem')}}</el-button>

          </el-form>
        </el-col>
      </el-row>
    </div>

    <el-card class="table-container">
      <el-table :data="dataList" @selection-change="selecChange">
        <!-- 多选 -->
        <el-table-column type="selection" width="55">
        </el-table-column>
        <!-- 发布时间 -->
        <el-table-column prop="createTime" :label="$t('pages.announcement.releaseTime')">
        </el-table-column>
        <!-- 类型 -->
        <el-table-column prop="type" :label="$t('pages.announcement.type')">
          <template slot-scope="scope">
            {{ scope.row.type | filterType }}
          </template>
        </el-table-column>
        <!-- 标题 -->
        <el-table-column prop="title" :label="$t('pages.announcement.headline')">
        </el-table-column>
        <!-- 发布组织 -->
        <el-table-column prop="areaCode" :label="$t('pages.announcement.releOrganization')">
        </el-table-column>
        <!-- 发布人 -->
        <el-table-column prop="createUser" :label="$t('pages.announcement.publisher')">
        </el-table-column>
        <!-- 公告详情 -->
        <el-table-column prop="updateTime" :label="$t('pages.announcement.relateDetails')">
            <template slot-scope="scope">
              <div>{{$t('pages.announcement.clickDetails')}}</div>
            </template>
        </el-table-column>
        <!-- 是否发布 -->
        <el-table-column prop="releaseStatus" :label="$t('pages.announcement.isRelease')">
          <template slot-scope="scope">
            <div>{{scope.row.releaseStatus | isUp}}</div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column
          prop="operate"
          label-class-name="text-center"
          class-name="text-center action"
          :label="$t('pages.announcement.operation')"
          width="180">
          <template slot-scope="scope">
            <!-- TODO:暂时隐藏 -->
            <!-- <a class="text-warning" @click.prevent="addOrUpdateHandle(scope.row)" href="/">{{ $t('pages.help.edit') }}</a> -->
            <a class="text-info" @click.prevent="releaseHandle(scope.row)" href="/">{{ $t('pages.announcement.release') }}</a>
            <a class="text-danger" @click.prevent="deleteHandle(scope.row)" href="/">{{ $t('pages.help.del') }}</a>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination @current-change="handleCurrentChange"
                     :current-page="pageIndex"
                     :page-size="pageSize"
                     layout="total, prev, pager, next, jumper"
                     :total="totalPage">
      </el-pagination>

    </el-card>

    <!--编辑、发布、新增-->
    <el-dialog :title="action === 'newsAc' ? $t('pages.announcement.newsProblem') : (action === 'edit' ? $t('pages.announcement.editProblem') : $t('pages.announcement.releaseProblem'))"
               :close-on-click-modal="false"
               :visible.sync="visible"
               width="80%"
               @close="onClose">
      <el-form :validate-on-rule-change="false"
               @keyup.enter.native.prevent="ok"
               :rules="action === 'view'? {}:dataRule"
               :model="current" label-width="80px" ref="dataForm">
        <el-form-item class="smallWin" :label="$t('pages.help.col_title')" prop="title">
          <el-input :placeholder="$t('pages.help.col_title')" v-model="current.title" :disabled="action === 'view'" />
        </el-form-item>
        <el-form-item class="smallWin" :label="$t('pages.announcement.type')" prop="types">
          <el-select v-model="current.types" placeholder="请选择">
            <el-option
              v-for="item in typeoOtions"
              :key="item.id"
              :label="en_cn=='zh-CN'?item.cnName:item.enName"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- TODO:暂时隐藏 -->
        <!-- <el-form-item class="smallWin" :label="$t('pages.announcement.organization')" prop="title"> -->
          <!-- <el-button plain @click="isShowOrgDialog=true">选择</el-button>
        </el-form-item> -->


        <el-form-item :label="$t('pages.help.question_detail')" prop="content">
          <ueditor @input="modleMsg" v-model="current.content"></ueditor>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click.prevent="ok">{{$t('pages.help.ok')}}</el-button>
        <el-button type="danger" @click="visible = false">{{$t('pages.help.cancel')}}</el-button>
      </span>
      <el-dialog
      width="50%"
      title="请选择区域"
      :visible.sync="isShowOrgDialog"
      append-to-body>
      <el-tree
        :data="areaList"
        show-checkbox
        node-key="code"
        ref="tree"
        :props="treeProps"
        >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click.prevent="saveOrg">{{$t('pages.help.ok')}}</el-button>
        <el-button type="danger" @click="isShowOrgDialog = false">{{$t('pages.help.cancel')}}</el-button>
        <el-button @click.prevent="resetChecked">{{$t('pages.announcement.reset')}}</el-button>
      </span>
      </el-dialog>
  </el-dialog>

  </div>
</template>

<script>
import axios from "@/utils/axios";
import ueditor from "@/components/ueditor";
import { mapGetters } from "vuex";
import { setTimeout } from 'timers';

export default {
  data() {
    return {
      msg: "",
      // 搜索条件
      formInline: {
        searchInput: this.$route.query.title || ""
      },
      dataList: [],
      areaList: [], //区域列表
      treeProps: {
        children: "childList",
        label: "label"
      },
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      visible: false,
      action: "news",
      dialogData: "",
      thatSelectArr: [],
      // 当前选择的
      current: {
        content: "",
        title: "",
        types: "",
        organization: ""
      },
      // 添加/修改数据规则
      dataRule: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        content: [
          { required: true, message: "问题详情不能为空", trigger: "blur" }
        ],
        types: [{ required: true, message: "类型不能为空", trigger: "change" }],
        organization: [
          { required: true, message: "接受组织不能为空", trigger: "change" }
        ]
      },
      typeoOtions: [],
      AzOptions: [],
      isShowOrgDialog: false //是否显示组织弹窗
    };
  },
  computed: {
    ...mapGetters({ en_cn: "common/en_cn" })
    // ...mapGetters([
    //   'en_cn'
    // ]),
  },
  created() {
    this.dialogOption();
    // this.dialogAz();
    const { query } = this.$route;
    this.pageIndex = query.pageNo ? parseInt(query.pageNo) : 1;
    this.current.title = query.title ? query.title : "";
    /* if(query.pageNo === 1 || !query.pageNo){
       this.pageIndex = 0
     } else {
       this.pageIndex = parseInt(query.pageNo)
     } */
    this.getDataList();
    this.getAreaList();
  },
  mounted() {},
  filters: {
    filterType(data) {
      switch (data) {
        case "1":
          return "暂定";
          break;
        case "2":
          return "暂定2";
          break;
        case "3":
          return "暂定3";
          break;
      }
    },
    isUp(data) {
      switch (data) {
        case "0":
          return "否";
          break;
        case "1":
          return "是";
      }
    }
  },
  methods: {
    resetChecked() {
      debugger
      this.$refs.tree.setCheckedKeys([],true);
      // this.$refs.tree.setCheckedNodes([],true);
    },
    saveOrg(data, arg1, arg2) {
      let leafOnly = true;
      // this.$emit('change', this.$refs.tree.getCheckedNodes(leafOnly))
      let checkArr = this.$refs.tree.getCheckedKeys(leafOnly);
      this.areaList.forEach(obj => {
        obj.childList.forEach(childObj => {
          childObj.select = false;
          checkArr.forEach(id => {
            if (id == childObj.id) {
              childObj.select = true;
            }
          });
        });
      });
      this.submitAreaList=[...this.areaList]
      this.isShowOrgDialog=false
      // this.$emit("change", this.data);
    },
    getAreaList() {
      this.$http({
        url: this.$http.adornUrl(
          "/prm-os-srv-sys/api/sysArea/queryAllAreaAndCountryTree"
        ),
        method: "post",
        data: this.$http.adornData({})
      }).then(data => {
        this.areaList = data.data;
      });
    },
    selectOrganization() {
      this.$dialog;
    },
    /* 弹窗类型请求 */
    dialogOption() {
      this.$http({
        url: this.$http.adornUrl(
          "/prm-os-srv-sys/sys/cpqsystemconfig/querySystemConfigByType"
        ),
        method: "post",
        data: this.$http.adornData({
          type: "Notice_Type"
        })
      }).then(data => {
        this.typeoOtions = data.cpqSystemConfig;
      });
    },

    /* 公告列表 */
    async getDataList() {
      let currentPage = this.pageIndex;
      let jsonData = {
        title: this.formInline.searchInput,
        pageNo: currentPage - 1,
        pageSize: this.pageSize
      };
      // console.log(Object.assign(jsonData, {pageNo: this.pageIndex}))
      this.$router.push({
        path: "sys-manage-announcement",
        query: Object.assign({}, jsonData, { pageNo: this.pageIndex })
      });

      this.$http({
        url: this.$http.adornUrl(
          "/prm-os-srv-anno/notice/cpqproductbulletin/queryProductBulletinList"
        ),
        method: "post",
        data: this.$http.adornData(jsonData)
      }).then(data => {
        console.log(data);
        let {
          code,
          page: { totalCount, pageSize, totalPage, currPage, list }
        } = data;
        if (!code) {
          this.dataList = list;
          // this.pageIndex = currPage
          // this.pageSize = pageSize
          this.totalPage = totalPage;
        }
      });
    },

    //分页
    handleCurrentChange(page) {
      this.pageIndex = page;
      this.getDataList();
    },

    //table 选中数组
    selecChange(arr) {
      this.thatSelectArr = arr;
      console.log(arr);
    },
    /*新增*/
    newHandle() {
      this.action = "newsAc";
      this.visible = true;
    },
    /* 单个删除 */
    deleteHandle(data) {
      this.$confirm("确定删除当前公告？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消"
      }).then(() => {
        const id = data.id;
        // todo 删除请求操作
        this.$http({
          url: this.$http.adornUrl(
            "/prm-os-srv-anno/notice/cpqproductbulletin/deleteProductBulletinById"
          ),
          method: "post",
          data: this.$http.adornData({
            id: id
          })
        }).then(data => {
          this.$message({
            type: "successs",
            message: "删除成功"
          });
          this.getDataList();
        });
      });
    },

    /*多选删除按钮*/
    delBtn() {
      const ids = this.thatSelectArr.map(data => data.id);
      if (ids.length < 1) {
        this.$alert("请选择至少选择一个选择项进行删除", "", {
          confirmButtonText: "确定"
        });
      } else {
        this.$confirm("确定删除多个公告？", "", {
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(
              "/prm-os-srv-anno/notice/cpqproductbulletin/deleteProductBulletinByIds"
            ),
            method: "post",
            data: this.$http.adornData({
              ids: ids
            })
          }).then(data => {
            this.$message({
              type: "successs",
              message: "删除成功"
            });
            this.getDataList();
          });
        });
      }
    },
    /* 编辑时的详情 */
    modleMsg(data) {
      // console.log(data)
      this.current.content = data;
    },

    /*编辑*/
    addOrUpdateHandle(data) {
      this.action = "edit";
      this.dialogData = data;
      this.visible = true;
      this.$http({
        url: this.$http.adornUrl(
          "/prm-os-srv-anno/notice/cpqproductbulletin/infoProductBulletin"
        ),
        method: "post",
        data: this.$http.adornData({
          id: data.id
        })
      }).then(data => {
        let {
          code,
          cpqProductBulletin: { title, type, areaCode, content }
        } = data;
        this.current = {
          title: title,
          types: type,
          organization: areaCode,
          content: content
        };
      });
    },

    /*发布*/
    releaseHandle(data) {
      this.action = "";
      this.dialogData = data;
      // this.visible = true

      this.$confirm("确定发布当前公告？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消"
      }).then(() => {
        const id = data.id;
        this.$http({
          url: this.$http.adornUrl(
            "/prm-os-srv-anno/notice/cpqproductbulletin/release"
          ),
          method: "post",
          data: this.$http.adornData({
            id: id
          })
        }).then(data => {
          this.$message({
            type: "successs",
            message: "发布成功"
          });
          this.getDataList();
          this.visible = false;
        });
      });
    },

    /*发布、新增、编辑接口处理*/
    ok() {
      this.$refs["dataForm"].validate(valid => {
        let { title, types, organization, content } = this.current;
        let jsonData = {
          title: title,
          type: types,
          areaCode: organization,
          content: content,
          sysAreaEntityList:this.submitAreaList
        };
        if (valid) {
          if (this.action === "edit") {
            // 编辑
            this.$http({
              url: this.$http.adornUrl(
                "/prm-os-srv-anno/notice/cpqproductbulletin/updateProductBulletin"
              ),
              method: "post",
              data: this.$http.adornData(
                Object.assign(jsonData, { id: this.dialogData.id })
              )
            }).then(data => {
              this.$message({
                type: "successs",
                message: "添加成功"
              });
              this.getDataList();
              this.visible = false;
            });
          } else if (this.action === "newsAc") {
            //新增

            this.$http({
              url: this.$http.adornUrl(
                "/prm-os-srv-anno/notice/cpqproductbulletin/saveProductBulletin"
              ),
              method: "post",
              data: this.$http.adornData(jsonData)
            }).then(data => {
              this.$message({
                type: "successs",
                message: "添加成功"
              });
              this.getDataList();
              this.visible = false;
            });
          } else {
            //发布？
          }
        } else {
          this.$message({
            type: "error",
            message: "请求错误，请重新检查"
          });
          return false;
        }
      });
    },

    //  弹窗关闭清除上次的校验结果
    onClose() {
      this.$refs.dataForm.resetFields();
      // this.$refs.dataForm.clearValidate()
      this.current = {};
      // console.log(this.current)
    }
  },
  components: {
    ueditor
  }
};
</script>

<style lang="scss" scoped>
.smallWin {
  width: 30%;
  display: inline-block;
  padding-left: 28px;
}
</style>
